<?php

namespace app\ask\controller;

use think\Controller;
// 引入邮箱发送类
use app\common\library\Email;

class Business extends Controller
{
   public function __construct()
   {
        parent::__construct();
        $this->BusinessModel=model('Business.Business');
        $this->SourceModel=model('Business.Source');
   }


   // 授权登录 
   public function login()
   {
        if($this->request->isPost())
        {
            // 接收临时凭证
            $code=$this->request->param('code','','trim');
            // var_dump($code);
            if(empty($code))
            {
                $this->error('服务器端临时凭证获取失败');
                exit;
            }

            // 授权
            $result=$this->code2Session($code);
            // 获取openid
            $openid=isset($result['openid']) ? $result['openid'] : '';

            if(empty($openid))
            {
                $this->error('获取openid失败');
                exit;
            }

            // 根据openid来找出是否存在的用户
            $business=$this->BusinessModel->where(['openid'=>$openid])->find();

            if($business)
            {
                // 有注册过
                unset($business['password']);
                unset($business['salt']);

                $this->success('授权登录成功',null,$business);
                exit;
            }else
            {
                $this->success("授权成功，请绑定账号",'/pages/business/login',['bind'=>$openid]);
                exit;
            }
        }
   }

   // 修改个人资料
   public function profile()
   {
        if($this->request->isPost())
        {
            $id = $this->request->param('id', 0, 'trim');
            $region = $this->request->param('region', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $email = $this->request->param('email', '', 'trim');
            $params = $this->request->param();

            // 查询
            $business=$this->BusinessModel->find($id);
            if(!$business)
            {
                $this->error('用户不存在，非法登录');
                exit;
            }

            // $avatar=$business['avatar'];
            // $path=pathinfo($avatar.PATHINFO_DIRNAME);
            // var_dump($avatar);
            // echo '<br>';
            // halt($path['dirname']);
            // exit;
            // 判断密码是否为空
            if(!empty($password))
            {
                $salt=build_ranstr();

                $params['salt']=$salt;
                $params['password']=md5($password.$salt);
            }

            // 修改了邮箱
            if($email !=$business['email'])
            {
                $params['auth']='0';
            }

            // 地区
            if(!empty($region))
            {
                // 获取地区路径
                $parent=model("Region")->where(['code'=>$region])->value('parentpath');

                // 转换为数组
                $list=explode(',',$parent);
                if(isset($list[0]))
                {
                    $params['province']=$list[0];
                }else
                {
                    $params['province']=null;
                }

                if(isset($list[1]))
                {
                    $params['city']=$list[1];
                }else
                {
                    $params['city']=null;
                }

                if(isset($list[2]))
                {
                    $params['district']=$list[2];
                }else
                {
                    $params['district']=null;
                }
            }
            //判断是否有图片上传
            if(isset($_FILES['avatar']) && $_FILES['avatar']['size']>0)
            {
                $result=build_upload('avatar');
                if($result['code'])
                {
                    $params['avatar']=$result['data'];
                }else
                {
                    $this->error($result['msg']);
                    exit;
                }
            }

            // 更新数据
            $result=$this->BusinessModel->validate('common/Business/Business')->isUpdate(true)->save($params);
            if($result===FALSE)
            {
                $this->error($this->BusinessModel->getError());
                exit;
            }

            // 判断是否有旧图片
            if(isset($params['avatar']))
            {
                $avatar=$business['avatar'];
                is_file(".".$avatar) && unlink(".".$avatar);
                // pathinfo($_SERVER['SCRIPT_FILENAME'].PATHINFO_BASENAME);//返回文件名
                $path=pathinfo($avatar.PATHINFO_DIRNAME);
                is_dir($path['dirname']) && @rmdir($path['dirname']);//删除空文件夹
            }

            // 重新查一遍
            $update=$this->BusinessModel->find($id);
            unset($update['password']);
            unset($update['salt']);

            $this->success('基本资料修改成功',null,$update);
            exit;
        }
   }  

   public function bind()
   {
        if($this->request->isPost())
        {
            $openid=$this->request->param('openid','','trim');
            $mobile=$this->request->param('mobile','','trim');
            $password=$this->request->param('password','','trim');

            if(empty($openid))
            {
                $this->error('授权登录openid获取失败');
                exit;
            }

            // 查询是否有注册过
            $business=$this->BusinessModel->where(['mobile'=>$mobile])->find();
            if($business)
            {
                // 验证密码
                $salt=$business['salt'];
                $password=md5($password.$salt);
                if($password != $business['password'])
                {
                    $this->error('密码不正确');
                    exit;
                }

                if(!empty($business['openid']))
                {
                    $this->error("此账号已被绑定");
                    exit;
                }

                //有账号注册过，但是openid的字段是空，所以要更新
                //自定义一个验证器
                $validate = [
                    [
                        'openid' => ['require', 'unique:business'],
                    ],
                    [
                        'openid.require'      => '授权字段未知',
                        'openid.unique'      => 'openid授权字段必须唯一',
                    ]
                ];

                // 组装更新数据
                $data=[
                    'id'=>$business['id'],
                    'openid'=>$openid
                ];

                $result=$this->BusinessModel->validate(...$validate)->isUpdate(true)->save($data);
                if($result===FALSE)
                {
                    $this->error($this->BusinessModel->getError());
                    exit;
                }

                // 查询最新的数据返回去
                $business=$this->BusinessModel->find($business['id']);
                unset($business['password']);
                unset($business['salt']);
                $this->success('绑定账号成功',null,$business);
                exit;
            }else
            {
                // 没有账号,直接注册
                // 生成一个密码盐
                $salt=build_ranstr();

                // 加密
                $password=md5($password.$salt);

                // 组装插入的数据
                $data=[
                    'mobile'=>$mobile,
                    'nickname'=>$mobile,
                    'password'=>$password,
                    'salt'=>$salt,
                    'money'=>0,
                    'deal'=>'0',
                    'auth'=>0,
                    'openid' => $openid
                ];

                // 找出客户来源
                $sourceid = $this->SourceModel->where(['name' => ['LIKE', "%问答社区%"]])->value('id');
                $data['sourceid'] = $sourceid;

                // 注册
                $result=$this->BusinessModel->validate('common/Business/Business')->save($data);

                if($result===FALSE)
                {
                    $this->error($this->BusinessModel->getError());
                    exit;
                }else
                {
                    // 直接拿最有一次插入的ID
                    $busid=$this->BusinessModel->id;

                    // 查询最新的数据并返回去
                    $business=$this->BusinessModel->find($busid);
                    unset($business['password']);
                    unset($business['salt']);
                    $this->success('注册账号并绑定成功',null,$business);
                    exit;
                }

            }
        }
   }

   // h5端和app端的登录
   public function signin()
   {
        if($this->request->isPost())
        {
            $mobile=$this->request->param('mobile','','trim');
            $password=$this->request->param('password','','trim');

            $business=$this->BusinessModel->where(['mobile'=>$mobile])->find();

            if(!$business)
            {
                $this->error('用户不存在');
                exit;
            }
            // 验证密码
            $salt=$business['salt'];
            $password=md5($password.$salt);
            if($password!=$business['password'])
            {
                $this->error('密码不正确');
                exit;
            }
            unset($business['password']);
            unset($business['salt']);
            $this->success('登录成功',null,$business);
            exit;
        }
   }  

    //发送邮件的方法
    public function email()
    {
        if($this->request->isPost())
        {
            $receiver = $this->request->param('email') ? $this->request->param('email') : '';
            if(empty($receiver))
            {
                $this->error('邮箱地址为空');
                exit;
            }

            $Ems = model('Ems');

            //判断是否有发送过验证码
            $where = [
                'event' => 'email',
                'email' => $receiver,
                'times' => 0
            ];

            $check = $Ems->where($where)->find();

            if($check)
            {
                $this->error('已重复发送验证码');
                exit;
            }

            $code = build_ranstr(5);

            // 插入到数据表中
            $data = [
                'event' => 'email',
                'email' => $receiver,
                'code' => $code,
                'times' => 0,
            ];
            //开启事务操作
            $Ems->startTrans();

            //插入
            $res = $Ems->save($data);

            //插入失败
            if(!$res)
            {
                $this->error('验证码插入失败');
                exit;
            }

            //实例化邮箱对象
            $email = new Email;

            $html = "<div>您的邮箱认证码为：<b>$code</b></div>";

            //获取系统配置
            $config = [
                'mail_type' => config('site.mail_type'),
                'mail_smtp_host' => config('site.mail_smtp_host'),
                'mail_smtp_port' => config('site.mail_smtp_port'),
                'mail_smtp_user' => config('site.mail_smtp_user'),
                'mail_smtp_pass' => config('site.mail_smtp_pass'),
                'mail_verify_type' => config('site.mail_verify_type'),
                'mail_from' => config('site.mail_from'),
            ];
            //合并系统配置
            \think\Config::set('site', array_merge(\think\Config::get('site'), $config));

            //发送邮件
            $result = $email->to($receiver)
                ->subject(config('site.name')."邮箱认证")
                ->message($html)
                ->send();

            if($result)
            {
                //事务提交
                $Ems->commit();
                $this->success('发送验证码成功，请注意查收');
                exit;
            }else
            {
                //回滚验证码
                $Ems->rollback();
                $this->error($email->getError());
                exit;
            }
        }
    }  


      //邮箱验证方法
      public function checkEmail()
      {
          if($this->request->isPost())
          {
              $id = $this->request->param('id',0,'trim');
              $email = $this->request->param('email','','trim');
              $code = $this->request->param('code', '', 'trim');

              $where = [
                  'event' => 'email',
                  'email' => $email,
                  'code' => $code,
              ];
  
              //加载模型
              $EmsModel = model('Ems');
              $BusinessModel = model('Business.Business');
  
              //开启事务
              $EmsModel->startTrans();
              $BusinessModel->startTrans();
  
              //数据查询
              $row = $EmsModel->where($where)->find();
  
              if(!$row)
              {
                  $this->error('邮箱认证码有误，请重新输入');
                  exit;
              }
  
              //更新用户状态
              $data = [
                  'id' => $id,
                  'auth'=>'1'
              ];
  
              $BusinessStatus = $BusinessModel->isUpdate(true)->save($data);
  
              if($BusinessStatus === FALSE)
              {
                  $this->error('邮箱认证失败');
                  exit;
              }
  
              //删除邮箱验证码
              $EmsStatus = $EmsModel->destroy($row['id']);
  
              if($EmsStatus === FALSE)
              {
                  $BusinessModel->rollback();
                  $this->error('删除邮箱认证码失败');
                  exit;
              }
  
              if($BusinessStatus === FALSE || $EmsStatus === FALSE)
              {
                  $EmsModel->rollback();
                  $BusinessModel->rollback();
                  $this->error('认证失败');
                  exit;
              }else
              {
                  //提交事务
                  $BusinessModel->commit();
                  $EmsModel->commit();
                  // 查询最新的数据并返回去
                  $business=$this->BusinessModel->find($id);
                  unset($business['password']);
                  unset($business['salt']);
                  $this->success("邮箱认证成功",null,$business);
                  exit;
              }
          }
      }

   /**
     * 获取小程序用户的唯一凭证 根据登录凭证code来获取 openid、session_key、unionid
     * https://developers.weixin.qq.com/miniprogram/dev/api/code2Session.html
     * @param  string|array $js_code 验证器名或者验证规则数组
     */
    protected function code2Session($js_code = null)
    {
        if($js_code)
        {
            // 自己小程序id和秘钥
            $appid = "wx1e58d841cf2d89fe";
            $secret = '3193a14ddb5331377caba0641dafd550';

            //微信服务器的请求地址
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$js_code&grant_type=authorization_code";

            //本控制器封装的方法
            $result = $this->https_request($url);

            //把结果转换成json
            $resultArr = json_decode($result,true);

            return $resultArr;
        }else
        {
            return false;
        }
    }

    //http请求
    protected function https_request($url,$data = null)
    {
        if(function_exists('curl_init')){
        $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
            if (!empty($data)){
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        }else{
            return false;
        }
    }
}
